/*
@Time : 2020/6/20 11:37
@Author : yaodongpo
@File : GenCodeController
@Software: GoLand
*/
package controllers

import (
	"beego-admin/gen"
	"git.9885.net/lib/go/common/db"
	"github.com/astaxie/beego"
	"strings"
)
// 代码生成
type GenCodeController struct {
	BaseController
}

func (self *GenCodeController) Prepare() {
	// 进行一些基础验证，这里空框架，暂时不验证

}

//@Title 已生成表
//@router / [get]
func (self *GenCodeController) TableList() {
	nameLike := self.GetString("table_name")
	genedTables := []map[string]string{}
	_, err := db.Session().Select("table_id", "table_name", "table_comment", "created_at", "updated_at").From("gen_tables").Where("table_name like '%" + nameLike + "%'").Load(&genedTables)
	gen.CheckErr(err)
	self.Data["key_word"] = nameLike
	self.Data["tables"] = genedTables
	self.TplName = "gened.tpl"
}

//@Title 未生成表
//@router /notGenList [get]
func (self *GenCodeController) NotGenList() {
	dbTableLike := beego.AppConfig.String("db_table_name")
	nameLike := self.GetString("table_name")
	if nameLike!=""{
		dbTableLike = nameLike
	}
	var genedTables []map[string]string
	_, err := db.Session().Select("table_name").From("gen_tables").Where("1").Load(&genedTables)
	gen.CheckErr(err)
	sliceTableName := []string{}
	for _,v := range genedTables{
		sliceTableName = append(sliceTableName, v["table_name"])
	}
	self.Data["key_word"] = nameLike
	tableNames := "1"
	if len(sliceTableName)>0{
		tableNames = strings.Join(sliceTableName, "','")
	}
	sqlStr := "select TABLE_NAME,TABLE_COMMENT,CREATE_TIME,UPDATE_TIME from TABLES where TABLE_SCHEMA='"+ beego.AppConfig.String("db.name") +"' and TABLE_NAME like '%" + dbTableLike + "%' and TABLE_NAME not in ('"+ tableNames +"');"
	tables := gen.GetListBySqlAndConnStr(sqlStr)
	self.Data["tables"] = tables
	self.TplName = "not_gen.tpl"
}

//@Title 代码生成设置
//@router /generateSet [get]
func (self *GenCodeController) GenerateSet() {
	self.TplName = "generateSet.tpl"
}

//@Title 批量初始化代码生成
//@router /batchInitSet [post]
func (self *GenCodeController) BatchInitSet() {
	tables := self.GetString("table_name_list")
	ok:=gen.InitGenSet(tables)
	if ok{
		self.AjaxInfo(1, "success")
	}else {
		self.AjaxInfo(0, "fail")
	}
}

//@Title 代码生成设置
//@router /generatePreview [get]
func (self *GenCodeController) GeneratePreview() {
	tName := self.GetString("tname")
	ret, err:= gen.TemplateRender(tName)
	gen.CheckErr(err)
	self.Data["ret"] = ret
	self.TplName = "generatePreview.tpl"
}

